import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class PropertiesEditor extends JFrame {
    private JTextArea textArea;
    private JButton saveButton;

    public PropertiesEditor() {
        setTitle("配置文件编辑器");
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        textArea = new JTextArea();
        add(new JScrollPane(textArea), BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        saveButton = new JButton("保存配置文件");
        buttonPanel.add(saveButton);
        add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String relativeFilePath = "src/config.properties";
                String configFilePath = new File(".").getAbsolutePath() + File.separator + relativeFilePath;
                if (writeFile(configFilePath)) {
                    JOptionPane.showMessageDialog(
                            PropertiesEditor.this,
                            "保存成功！",
                            "操作成功",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                }
            }
        });

        // 启动时自动加载配置文件
        String configFilePath = new File(".").getAbsolutePath() + File.separator + "src" + File.separator + "config.properties";
        readFile(configFilePath);

        setLocationRelativeTo(null);
    }

    private boolean writeFile(String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(textArea.getText());
            return true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Error writing file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    private void readFile(String filePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            textArea.setText(stringBuilder.toString());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Error reading file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PropertiesEditor().setVisible(true);
            }
        });
    }
}